package ch.lom.clemens.android.bibliography;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import ch.lom.clemens.android.bibliography.data.MDocument;

public class DocumentActivity extends Activity {

	public static MDocument m_curDoc = null;
	public static DocumentActivity singleton;
	
	private static List<Map<String,Object>> m_groupData = new ArrayList<Map<String,Object>>();
	private static List<List<Map<String,Object>>> m_childData = new ArrayList<List<Map<String,Object>>>();
	
	private ExpandableListAdapter m_listAdapter;
	
	private static final String NAME = "NAME";
	private static final String TEXT = "TEXT";
	private static final String CHILDREN = "CHILDREN";
	
	private static final String TAGS        = "Tags";
	private static final String ABSTRACT    = "Abstract";
	private static final String PUB_DETAIL  =  "Publication details";
	private static final String NOTES       = "Notes";
	private static final String URLS        = "URLs";
	private static final String IDENTIFIERS = "Identifiers";
	private static final String DISCIPLINE  = "Discipline";

	/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.document);
        
        singleton = this;
        
        m_btnOpenPDF = (Button)findViewById(R.id.docOpenPDF);
        m_btnOpenPDF.setEnabled(false);
        m_btnOpenPDF.setOnClickListener(m_openPDF);

        ExpandableListView lv = (ExpandableListView)findViewById(R.id.docTagList);
        
		m_listAdapter = new SimpleExpandableListAdapter(this, 
				//m_groupData, android.R.layout.simple_expandable_list_item_1, new String[]{NAME}, new int[]{android.R.id.text1},
				m_groupData, R.layout.documentheader, new String[]{NAME}, new int[]{R.id.dochead_text},
				m_childData, R.layout.document_item, new String[]{TEXT}, new int[]{R.id.docitem_text});
		lv.setAdapter(m_listAdapter);
    }
    
    
    class MyFilenameFilter implements FilenameFilter {
    	private String m_title;
    	public MyFilenameFilter(String title) {m_title = title;}
		public boolean accept(File dir, String filename) {
			return filename.endsWith(".pdf") && filename.indexOf(m_title) != -1;
		}
	}   
    
    private void addGroupListEntry(String groupName, String childText) {
    	addGroupListEntry(groupName, new String[]{childText});
    }
    
    private void addGroupListEntry(String groupName, String [] childrenText) {
		Map<String,Object> curGroupMap = new HashMap<String,Object>();
        List<Map<String,Object>> children = new ArrayList<Map<String,Object>>(); 
        Map<String,Object> childdata;
		
        m_groupData.add(curGroupMap);
        m_childData.add(children);
        
        curGroupMap.put(NAME,groupName);
        curGroupMap.put(CHILDREN,children); // save for reference

        // allow to give no items
        if (childrenText != null) {
	        for (int i=0; i<childrenText.length; i++) {
		        childdata = new HashMap<String,Object>();
		        children.add(childdata);
		        if (childrenText[i] == null || childrenText[i].length()==0) {
		        	childdata.put(TEXT, "no data");
		        } else {
		        	childdata.put(TEXT, childrenText[i]);
		        }
	        }
        }
    }
    
    private void getDocumentData(MDocument document) {

    	String strTitle = null;
    	m_groupData.clear();
    	m_childData.clear();
    	
    	try {
			if (document == null) {
				((TextView)findViewById(R.id.docTitle)).setText("Could not retrieve document info");
			}
			
			TextView tvTitle = (TextView)findViewById(R.id.docTitle);
			strTitle = document.getTitle();
			tvTitle.setText(strTitle);
			
			TextView tvAuthors = (TextView)findViewById(R.id.docAuthors);
			tvAuthors.setText(document.getAuthorsString());

			addGroupListEntry(PUB_DETAIL, document.getPubOutlet());
			addGroupListEntry(ABSTRACT, document.getAbstract());
			addGroupListEntry(TAGS, document.getTags());
			addGroupListEntry(NOTES, document.getNotes());
			addGroupListEntry(URLS, document.getURLs());
			
			
			Map<String,String> identifiers = document.getIdentifiers();
			String [] strIdentifiers = new String[identifiers.size()];
			int i = 0;
			for (String key : identifiers.keySet()) {
				strIdentifiers[i++] = key + ": " + identifiers.get(key); 
			}
			addGroupListEntry(IDENTIFIERS, strIdentifiers);
			
			Map<String,String> discipline = document.getDiscipline();
			String [] strDiscipline = new String[discipline.size()];
			int j = 0;
			for (String key : discipline.keySet()) {
				strDiscipline[j++] = key + ": " + discipline.get(key); 
			}
			addGroupListEntry(DISCIPLINE, strDiscipline);
			
			
/*			
			
			TextView tvNotes = (TextView)findViewById(R.id.docNotes);
			tvNotes.setText("Notes:"+document.getNotes());
			
			TextView tvURL = (TextView)findViewById(R.id.docURL);
			tvURL.setText("URL: " + document.getURL());
			
			//TextView tvDOI = (TextView)findViewById(R.id.docDOI);
			//JSONObject ids = document.getJSONObject("identifiers");
			//tvDOI.setText("DOI: http://dx.doi.org/" + ids.getString("doi"));

			m_listAdapter.notifyDataSetChanged();
*/			
    	} catch (Exception e) {
			String str = "Got a " + e.getClass().getName() + ": " + e.getMessage();
			Toast toast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG);
			toast.show();
		}
    	
    	boolean bFileFound = false;
		String state = Environment.getExternalStorageState();
    	if (strTitle != null && (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))) {
	    	// determine whether the PDF is available
    		File fDirectory =  new File(DOCSDIR);
    		
    		if (fDirectory.exists() && fDirectory.isDirectory()) {
    			File [] files = fDirectory.listFiles(new MyFilenameFilter(strTitle));
    			
    			if (files.length > 0) {
    				m_btnOpenPDF.setEnabled(true);
    				m_openPDF.pdfdoc = files[0];
    				bFileFound = true;
    			}
    		}
    	} 
    	
    	if (! bFileFound ) {
    		m_btnOpenPDF.setEnabled(false);
            m_openPDF.pdfdoc = null;
    	}
    	
    }
    
    public static String DOCSDIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mendeley";
    
    public void onResume() {
    	super.onResume();

    	getParent().setTitle( getString(R.string.app_name) );
    	
    	if (m_curDoc != null) {
    		getDocumentData(m_curDoc);
    	}
    }
    
    
	class OpenPDF implements OnClickListener {
		public File pdfdoc;
		public void onClick(View v) {
			Uri fileUri = Uri.fromFile(pdfdoc);
			
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(fileUri, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            try {
                startActivity(intent);
            } 
            catch (ActivityNotFoundException e) {
                Toast toast = Toast.makeText(getApplicationContext(),"No PDF viewer available",Toast.LENGTH_SHORT);
                toast.show();
            }	    				
		}
	};
	OpenPDF m_openPDF = new OpenPDF();
	
	Button m_btnOpenPDF;
    
}
